package com.example.springboot.service.impl;

import com.example.springboot.controller.dto.ChildDTO;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.Child;
import com.example.springboot.entity.Person;
import com.example.springboot.service.IChildService;
import com.example.springboot.service.IPersonService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.example.springboot.utils.UidGenerator.generateUUID;

/**
 * @author danqihao
 */
@Service
public class PersonService {

    @Autowired
    private IPersonService iPersonService;

    @Autowired
    private IChildService iChildService;


    public int insertChildren(List<ChildDTO> children) {
        return 0;
    }

    public void addPerson(Person person) {
        String uid = generateUUID();
        person.setId(uid);
        iPersonService.addPerson(person);
        List<Child> children = person.getChildren();
        if (person.getChildren() != null) {
            children.forEach(child -> {
                String cUid = generateUUID();
                child.setId(cUid);
                child.setEmployeeId(uid);
                iChildService.insertChild(child);
            });
        }
    }

    public List<Child> getPersonList() {
        return iPersonService.getPersonList();
    }

    public PageInfo<Person> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Person> personList = iPersonService.listByCondition(baseRequest);
        if (personList != null && !personList.isEmpty()) {
            personList.forEach(person -> {
                String employeeId = person.getId();
                if (employeeId != null && !employeeId.isEmpty()) {
                    List<Child> childList = iChildService.selectChildrenByEmployeeId(employeeId);
                    person.setChildren(childList);
                }
            });
        }
        if (personList != null) {
            return new PageInfo<>(personList);
        }
        return new PageInfo<>(iPersonService.listByCondition(baseRequest));
    }

}
